<?php

declare (strict_types=1);
namespace App\Model;

use Hyperf\DbConnection\Model\Model;
use Hyperf\Database\Model\Builder;

/**
 * 优惠券日志model
 *
 * @Author czm
 * @DateTime 2020-04-16
 */
class CouponLog extends Model
{
    use SelectTrait;
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'coupon_log';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['openid','coupon_id','order_no','unique_num','type','type_explain','lottery_id','amount','add_time','update_time','start_time','end_time','is_del'];
    protected $guarded=['id'];
    
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'add_time'=>'datetime:Y-m-d H:i:s',
        'update_time'=>'datetime:Y-m-d H:i:s',
        // 'start_time'=>'datetime:Y-m-d H:i:s',
        // 'end_time'=>'datetime:Y-m-d H:i:s',
    ];

    const CREATED_AT = 'add_time';
    const UPDATED_AT = 'update_time';
    // protected $dateFormat = 'U';
    protected $dateFormat = 'U';
    protected function boot(): void
    {   
        $this->bootTraits();
        //model 软删除过滤 避免每次查询都添加is_del条件 去除条件添加withoutGlobalScope
        $this->addGlobalScope('is_del', function(Builder $builder) {
            $builder->where($this->table.'.is_del',1);
        });
        // var_dump($columns);
    }

    
    //映射type_explain
    public function getTypeExplainMappingAttribute(){
        $enum=array_unique(explode(',',$this->attributes['type_explain']));
        sort($enum);
        foreach($enum as &$val){
            switch($val){
                case 1:$val='话费充值'; break;
                case 2:$val='赠送好友'; break;
                case 3:$val='抽奖'; break;
                case 4:$val='好友赠送'; break;
                case 5:$val='话费充值抵扣'; break;
                case 6:$val='话费退款返还'; break;
                case 7:$val='油卡充值抵扣'; break;
                case 8:$val='油卡退款返还'; break;
                case 9:$val='油卡充值'; break;
            }
        }
        return $this->attributes['type_explain_mapping']=implode("/",$enum);

    }

    //映射type
    public function getTypeMappingAttribute(){

            switch($this->attributes['type']){
                case 1:$val='获取'; break;
                case 2:$val='失去'; break;
                default:$val='';break;
            }
        return $val;
    }

    //一对一获取用户
    public function wxuser(){
        return $this->hasOne(Wxuser::class,'openid','openid');
    }

    //一对一获取红包
    public function coupon(){
        return $this->hasOne(coupon::class,'id','coupon_id');
    }

 
    
}